package vip.idiy.anwei_android_iot.utils;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * ClassName MQTTUtil
 * describe:
 * Created: 勇
 * Email:118085890@qq.com
 * Version: 1.0
 * Create in 20:19 2023/4/27
 */
public class MQTTUtil {
    // 单例模式
    private static MQTTUtil instance;
    // MQTT客户端
    private MqttClient mqttClient;
    // MQTT连接选项
    private MqttConnectOptions mqttOptions;
    // MQTT服务器地址
    private static String MQTT_SERVER ;
    // MQTT用户名
    private static String MQTT_USER ;
    // MQTT密码
    private static String MQTT_PASSWORD ;
    // MQTT客户端ID
    private static final String MQTT_CLIENT_ID = "anwei-android-iot";
    // 订阅主题
    private final String[] TOPICS = {"anwei_iot_device_sub/#", "$SYS/brokers/+/clients/#"};

    public static String getMqttServer() {
        return MQTT_SERVER;
    }

    public static void setMqttServer(String mqttServer) {
        MQTT_SERVER = mqttServer;
    }

    public static String getMqttUser() {
        return MQTT_USER;
    }

    public static void setMqttUser(String mqttUser) {
        MQTT_USER = mqttUser;
    }

    public static String getMqttPassword() {
        return MQTT_PASSWORD;
    }

    public static void setMqttPassword(String mqttPassword) {
        MQTT_PASSWORD = mqttPassword;
    }

    // 私有构造函数
    private MQTTUtil() {
    }

    public static MQTTUtil getInstance() { // 获取单例对象
        if (instance == null) {
            instance = new MQTTUtil();
        }
        return instance;
    }

    /**
     * 初始化MQTT客户端并连接服务器
     *
     * @param mqttCallback      处理MQTT事件的回调
     * @param onConnectListener 处理连接事件的监听器
     */
    public void connectMQTT(MqttCallback mqttCallback, OnConnectListener onConnectListener) {
        try {
            mqttClient = new MqttClient(MQTT_SERVER, MQTT_CLIENT_ID, new MemoryPersistence());// 创建MQTT客户端
            mqttOptions = new MqttConnectOptions();// MQTT连接设置
            mqttOptions.setCleanSession(true);// 设置是否清空session
            mqttOptions.setUserName(MQTT_USER);// 设置连接的用户名
            mqttOptions.setPassword(MQTT_PASSWORD.toCharArray());// 设置连接的密码
            mqttOptions.setConnectionTimeout(10);// 设置超时时间 单位为秒
            mqttOptions.setKeepAliveInterval(20);// 设置会话心跳时间 单位为秒
            mqttClient.setCallback(mqttCallback);// 设置MQTT回调
            mqttClient.connect(mqttOptions);// 连接MQTT服务器
            onConnectListener.onSuccess();// 连接成功回调
        } catch (MqttException e) {
            e.printStackTrace();
            onConnectListener.onFailure();// 连接失败回调
        }
    }

    /**
     * 判断MQTT客户端是否连接
     *
     * @return true表示已连接，false表示未连接
     */
    public boolean isConnect() {
        return mqttClient != null && mqttClient.isConnected();
    }

    /**
     * 断开MQTT客户端连接
     */
    public void disconnect() {
        try {
            mqttClient.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 订阅MQTT主题
     */
    public void subscribeMQTT() {
        try {
            mqttClient.subscribe(TOPICS, new int[]{1, 1});
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送MQTT消息
     *
     * @param topic   消息主题
     * @param message 消息内容
     */
    public void publishMQTT(String topic, String message) {
        try {
            MqttMessage mqttMessage = new MqttMessage(message.getBytes());
            mqttMessage.setQos(1);// 设置消息质量
            mqttClient.publish(topic, mqttMessage);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    public interface OnConnectListener {
        void onSuccess();

        void onFailure();
    }
}